'use strict';

angular.module('app')
  .controller('SearchCtrl', [ '$scope', 'growl', 'svcMain', 'svcState', function ($scope, growl, svcMain, svcState) {

    if(!svcState.isLoggedIn()) {
        svcState.gotoLogin();
        return;
    }

    $scope.dataReady = false;
    $scope.fetchInProgress = false;
    $scope.noMatchesFound = false;

    $scope.searchCriteria = '';

    $scope.$watch("searchCriteria", $.debounce(500, function () {
        if ($scope.searchCriteria.length <= 2) {

            $scope.dataReady = false;
            $scope.fetchInProgress = false;
            $scope.$apply();

        } else {
            $scope.fetchInProgress = true;
            $scope.$apply();

            svcMain.quickSearch($scope.searchCriteria).then(function (resp) {

                console.log('quickSearch', resp);

                if (resp.statusCode) {
                    $scope.fetchInProgress = false;
                    if (resp.statusCode == 'SUCCESS') {
                      $scope.members = resp.object;
                      $scope.dataReady = (resp.object && resp.object.length && resp.object.length > 0);
                      if (!$scope.dataReady)
                        growl.warning("No members matching specified criteria!");
                    }
                    else if (resp.statusCode == 'ERROR_LOGIN_REQUIRED') {
                        svcState.gotoLogin();
                    }
                    else {
                      growl.error(resp.statusCode + (resp.userFriendlyMessage ? ': ' + resp.userFriendlyMessage : ''));
                    }

                } else {
                    growl.error('Invalid response from Server');
                }
            });

        }
    }));


  }]);

